import { useReactive } from "ahooks";
import { useEffect } from "react";
import localforage from "localforage";
import { useModel } from "umi";
import { useOrganizationMember } from "@share-code/public";

import appInfo from "../../publish/app.js";

function personInfoModel() {
    const { graphqlFetch } = useModel("global");
    const { loadOrganizationMemberInfo } = useOrganizationMember(graphqlFetch);

    let state = useReactive({
        currentPerson: "",
        currentPersonRealName: "",
        accountInfo: {},
        baseInfo: {},
        loginInfo: {},
        memberInfo: {},
        identity: "guest", // 当前用户身份：guest 游客(未登录); localLogined  本地登录; remoteLogined 公共认证中心登录; temporaryLogined 公共认证中心临时登录
    });

    const initData = async () => {
        state.currentPerson = await localforage.getItem(appInfo.appUuid + "-当前个人");
        state.currentPersonRealName = await localforage.getItem(appInfo.appUuid + "-当前个人姓名");
    };

    useEffect(() => {
        initData();
    }, []);

    useEffect(() => {
        const remotePersonInfo = remote.getGlobal("personInfo");
        for (let key in remotePersonInfo) {
            state[key] = remotePersonInfo[key];
        }
    }, []);

    const loadMemberInfo = async () => {
        let res = await loadOrganizationMemberInfo(state.baseInfo.uuid);
        state.memberInfo = res || {};
    };

    useEffect(() => {
        state.baseInfo?.uuid && loadMemberInfo();
    }, [state.baseInfo]);

    const setPersonStateValue = (obj) => {
        for (let key in obj) {
            state[key] = obj[key];
        }
    };

    const setCurrentPerson = (uuid, realName) => {
        state.currentPerson = uuid;
        state.currentPersonRealName = realName;
        localforage.setItem(appInfo.appUuid + "-当前个人", uuid);
        localforage.setItem(appInfo.appUuid + "-当前个人姓名", realName);
    };

    return {
        ...state,
        setCurrentPerson,
        setPersonStateValue,
    };
}

export default personInfoModel;
